//引入请求接口
import {reqLogin,reqUserInfo,reqLoginOut} from '@/api/'
export default {
    state: () => ({
        userInfo:{},
        token:localStorage.getItem('token')||''
    }),
    mutations:{
       LOGIN(state,data){
            state.token=data
       },
       USERINFO(state,data){
         state.userInfo=data
       },
       CLEAR(state){
            state.token=''
            state.userInfo={}
       }
    },
    actions: {
        async  login({commit},{phone,password}){
            try{
                const success = await reqLogin(phone,password)
               
                if(success.code===200){
                    commit('LOGIN',success.data.token)
                    if(!localStorage.getItem('token')){
                        localStorage.setItem('token',success.data.token)
                    }
                    return 'ok'
                }else{
                    return Promise.reject(new Error('登入失败'))
                }
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
           
        },
        async  loginOut({commit}){
            try{
                const success = await reqLoginOut()
                if(success.code===200){
                    commit('CLEAR')
                    localStorage.removeItem('token')
                    return 'ok'
                }else{
                    return Promise.reject(new Error(success.message))
                }
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
           
        },
        async userInfo({commit}){
                const success = await reqUserInfo()
                if(success.code===200){
                    commit('USERINFO',success.data)
                }else{
                    return Promise.reject(new Error(success.message))
                }
            
        }
    }
}